<template>
  <PerfectTableComponent
    :loadTableList="loadTableList"
    :changePageSize="changePageSize"
    :changePage="changePage"
    :removeQueryField="removeQueryField"
    :clearQuery="clearQuery"
    v-model:query="query"
    title="库位"
    ref="tableRef"
    :queryFormHeaders="queryFormHeaders"
    :table="table"
    :tableColumns="tableColumns"
    :showTableIndex="false"
    :operatorColumnWidth="300"
    :baseUrl="urls.API_URL_BACKSTAGE_WMS_WMSWAREHOUSESEAT"
    v-model:form="form"
    :formHeader="formHeader"
    @afterOpenDialogOfEditRow="afterOpenDialogOfEditRow"
    @beforeFormSubmit="beforeFormSubmit"
    @afterOpenDialogOfAddRow="afterOpenDialogOfAddRow"
    @afterSubmitSuccessOfAddRow="afterSubmitSuccessOfAddRow"
  >
    <!-----------------------------表格查询表单自定义元素----------------------------------------->
    <template #query_form_warehouseId>
      <WmsWarehouseCascadeSelectComponent
        ref="wmsWarehouseCascadeSelectQueryComponentRef"
        v-model:warehouseId="query['warehouseArea.warehouse.id']"
        v-model:warehouseAreaId="query['warehouseArea.id']"
        :showWarehouseSeat="false"
      />
    </template>
    <!-----------------------------表格自定义列----------------------------------------->
    <!--所属仓库名称-->
    <template #table_column_warehouseName="scope: any">
      {{ scope.row.warehouseArea != null ? scope.row.warehouseArea.warehouse.name : '' }}
    </template>
    <!--所属库区名称-->
    <template #table_column_warehouseAreaName="scope: any">
      <el-link
        type="primary"
        @click="
          router.push({
            path: '/backstage/wms/warehousearea',
            query: {
              warehouseId: scope.row.warehouseArea.warehouse.id
            }
          })
        "
      >
        {{ scope.row.warehouseArea != null ? scope.row.warehouseArea.name : '' }}</el-link
      >
    </template>
    <!-----------------------------表单自定义元素----------------------------------------->
    <template #dialog_form_warehouseAreaId>
      <WmsWarehouseCascadeSelectComponent
        ref="wmsWarehouseCascadeSelectFormComponentRef"
        v-model:warehouseId="form['warehouseId']"
        v-model:warehouseAreaId="form['warehouseAreaId']"
        :showWarehouseSeat="false"
      />
    </template>
  </PerfectTableComponent>
</template>

<script setup lang="ts">
import PerfectTableComponent from '@/components/base/table/PerfectTableComponent.vue';
import WmsWarehouseCascadeSelectComponent from '@/components/wms/WmsWarehouseCascadeSelectComponent.vue';
import { defineAsyncComponent, nextTick, onMounted, provide, reactive, ref } from 'vue';
import useTableList from '@/api/hooks/useTableList';
import type { FormHeader, ResponseData, TableColumn } from '@/types/interface/base_interface';
import urls from '@/api/request/urls';
import { getDict } from '@/api/dict';
import type { WarehouseArea, WarehouseSeat } from '@/types/interface/wms_interface';
import Request from '@/api/request/request';
// 导入路由
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter(); // 创建路由对象
// 表格工具必备参数。这里为了等待库区模块传递过来的参数，选择延迟加载
const { table, query, loadTableList, removeQueryField, clearQuery, changePageSize, changePage } = useTableList(
  urls.API_URL_BACKSTAGE_WMS_WMSWAREHOUSESEAT,
  true,
  {},
  false
);
// 将表格刷新函数传到子容器
provide('loadTableList', loadTableList);

//获取其他组件传递过来的值==========================================================
//获取库区模块传递过来的库区id（如果是从库区模块跳转来的）
const warehouseAreaIdOfParam: string | undefined = route.query.warehouseAreaId as string | undefined;
//赋值给query值
if (typeof warehouseAreaIdOfParam != 'undefined' && warehouseAreaIdOfParam != null && warehouseAreaIdOfParam.length > 0) {
  query.value['warehouseArea.id'] = warehouseAreaIdOfParam;
}
//获取仓库模块传递过来的仓库id（如果是从仓库模块跳转来的）
const warehouseIdOfParam: string | undefined = route.query.warehouseId as string | undefined;
//赋值给query值
if (typeof warehouseIdOfParam != 'undefined' && warehouseIdOfParam != null && warehouseIdOfParam.length > 0) {
  query.value['warehouse.id'] = warehouseIdOfParam;
}
//执行查询，刷新表格
loadTableList();

//查询==========================================================
const queryFormHeaders = ref<FormHeader[]>([]);

//表格==========================================================
// 表格插件ref对象1
const tableRef = ref();

//表格列
// 定义表格所有的列字段信息
const tableColumns = ref<TableColumn[]>([]);

//表单==========================================================
//表单对象
const form = ref<WarehouseSeat>({});
//表单元素类型
const formHeader = ref<FormHeader[]>([]);

const getWmsWarehouse = async () => {
  const resData: any = await new Request(urls.API_URL_BACKSTAGE_WMS_WMSWAREHOUSE + '/all').get();
  if (resData.success) {
    return resData.data;
  }
};
// const getWmsWarehouseArea = async () => {
//   const resData: any = await new Request(urls.API_URL_BACKSTAGE_WMS_WMSWAREHOUSEAREA + '/all').get();
//   if (resData.success) {
//     return resData.data;
//   }
// };
//查询组件中的仓库级联菜单
const wmsWarehouseCascadeSelectQueryComponentRef = ref();
onMounted(async () => {
  //获取仓库列表
  const warehouses = await getWmsWarehouse();
  //定义优先级选项。放在mounted中执行时，要将引用改变量的属性也放进来。
  const enabledDict = await getDict('启用状态', 'boolean');
  queryFormHeaders.value = [
    // 查询表单
    {
      prop: 'name',
      label: '库位名称'
    },
    {
      prop: 'warehouseId',
      label: '仓库选择',
      propAsNames: ['warehouseArea.warehouse.id', 'warehouseArea.id'],
      type: 'custom'
    },
    // {
    //   prop: 'warehouseId',
    //   propAsName: 'warehouse.id',
    //   label: '所属仓库',
    //   type: 'selectObject',
    //   list: warehouses,
    //   config: {
    //     valueKey: 'id',
    //     defaultProp: {
    //       value: 'id',
    //       label: 'name'
    //     }
    //   }
    // },
    {
      prop: 'enabled',
      label: '是否启用',
      type: 'select',
      list: enabledDict
    }
  ];
  //等待dom加载完，再执行下一步
  await nextTick();
  //设置查询表单仓库级联菜单的初始值
  if (typeof query.value['warehouse.id'] !== 'undefined') {
    wmsWarehouseCascadeSelectQueryComponentRef.value.setWarehouse(query.value['warehouse.id']);
  } else if (typeof query.value['warehouseArea.id'] !== 'undefined') {
    wmsWarehouseCascadeSelectQueryComponentRef.value.setWarehouseArea(query.value['warehouseArea.id']);
  }

  //表格对象
  tableColumns.value = [
    {
      label: '库位编码',
      prop: 'code',
      width: 100,
      fixed: true
    },
    {
      label: '库位名称',
      prop: 'name',
      fixed: true
    },
    {
      label: '所属仓库',
      prop: 'warehouseName',
      type: 'custom',
      width: 100
    },
    {
      label: '所属库区',
      prop: 'warehouseAreaName',
      type: 'custom',
      width: 100
    },
    {
      label: '物料种类',
      prop: 'materialInventoryDetailNumber',
      width: 100
    },
    {
      label: '启用状态',
      prop: 'enabled',
      width: 100,
      type: 'dict',
      dict: enabledDict
    },
    {
      label: '创建时间',
      prop: 'createTime',
      width: 180
    },
    {
      label: '最后编辑时间',
      prop: 'updateTime',
      width: 180
    }
  ];
  // 添加编辑表单
  formHeader.value = [
    {
      prop: 'warehouseAreaId',
      label: '所属库位',
      type: 'custom',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '库位编码',
      prop: 'code',
      rules: [
        {
          max: 50,
          message: '长度在不能超过50个字符',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '库位名称',
      prop: 'name',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        },
        {
          max: 30,
          message: '长度不能超过30个字符',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '是否启用',
      prop: 'enabled',
      type: 'select',
      list: enabledDict,
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    }
  ];
});
//获取仓库级联对象
const wmsWarehouseCascadeSelectFormComponentRef = ref();
//在添加行的动作以前
// const beforeAddRow = async () => {
//   //传入初始值
//   form.value = {
//     enabled: true
//   };
// };
//如果添加记录前需要执行对话框中的组件函数（即在组件初始化再调用），则调用这个函数
const afterOpenDialogOfAddRow = async () => {
  form.value = {
    enabled: true
  };
  //如果从库区传递了默认值过来
  if (typeof warehouseAreaIdOfParam != 'undefined' && warehouseAreaIdOfParam != null && warehouseAreaIdOfParam.length > 0) {
    //并且后面没有重新在查询栏更换默认库位的值（如果更换了就应该是不再使用原来的库位），则默认创建的库位就是该库位
    if (warehouseAreaIdOfParam === query.value['warehouseArea.id']) {
      form.value.warehouseAreaId = warehouseAreaIdOfParam;
      if (wmsWarehouseCascadeSelectFormComponentRef.value !== undefined) {
        //设置仓库级联选择组件的值
        wmsWarehouseCascadeSelectFormComponentRef.value.setWarehouseArea(warehouseAreaIdOfParam);
      }
    }
  }
};
//在添加成功提交后调用。
// 解释：因为afterOpenDialogOfAddRow这个函数只有在重新打开对话框时才会使用，而添加成功后会保持表单对话框不关闭，因此这里需要手动来重新加载表单中的仓库级联选择框
const afterSubmitSuccessOfAddRow = () => {
  //设置仓库级联选择组件的值
  if (typeof warehouseAreaIdOfParam != 'undefined' && warehouseAreaIdOfParam != null && warehouseAreaIdOfParam.length > 0) {
    if (warehouseAreaIdOfParam === query.value['warehouseArea.id']) {
      wmsWarehouseCascadeSelectFormComponentRef.value.setWarehouseArea(warehouseAreaIdOfParam);
    }
  }
};
//在编辑行读取后端记录后需要修改的地方
const afterOpenDialogOfEditRow = async (formEdit: WarehouseSeat) => {
  //重新封装表单对象的值
  if (formEdit.warehouseArea != null) {
    formEdit.warehouseAreaId = formEdit.warehouseArea.id;
    //设置仓库级联选择组件的值（第一次打开对话框可能为Null)
    if (wmsWarehouseCascadeSelectFormComponentRef.value !== undefined) {
      wmsWarehouseCascadeSelectFormComponentRef.value.setWarehouseArea(formEdit.warehouseAreaId);
    }
  }
};

// const afterOpenDialogOfEditRow = () => {
//   //设置仓库级联选择组件的值
//   wmsWarehouseCascadeSelectFormComponentRef.value.setWarehouseArea();
// };

//在表单提交前对对象进行封装
const beforeFormSubmit = () => {
  if (form.value.warehouseAreaId != null) {
    form.value.warehouseArea = {
      id: form.value.warehouseAreaId
    };
  }
};
</script>

<style scoped></style>
